﻿using FileStorage.Common;
using FileStorage.Models.Entity;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FileStorage.Models
{
    public static class FileDao
    {
        public static Node queryById(string fileId, DapperHelper cn)
        {
            return cn.FirstOrDefault<Node>("SELECT * FROM `fs_file` WHERE FileId = @fileId;", new { fileId });
        }

        public static List<Node> queryBySomeFolder(string fileId, DapperHelper cn)
        {
            return cn.Query<Node>("SELECT * FROM `fs_file` WHERE FileParentFolder IN (SELECT FileParentFolder FROM `fs_file` WHERE FileId = @fileId) AND FileDeletionDate IS NULL LIMIT 0,2147483647;", new { fileId }).ToList();
        }

        public static long countByParentFolderId(string pfid, DapperHelper cn)
        {
            // return cn.FirstOrDefault<long>("SELECT COUNT(FileId) FROM `fs_file` WHERE FileParentFolder = @pfid AND FileDeletionDate IS NULL;", new { pfid });
            return cn.FirstOrDefault<long>("SELECT COUNT(FileId) FROM `fs_file` WHERE FileParentFolder = @pfid;", new { pfid });
        }

        public static List<Node> queryByParentFolderIdSection(string pfid, long offset, int rows, DapperHelper cn)
        {
            return cn.Query<Node>("SELECT * FROM `fs_file` WHERE FileParentFolder = @pfid AND FileDeletionDate IS NULL limit @offset,@rows;", new { pfid, offset, rows }).ToList();
        }

        public static List<Node> queryByParentFolderId(string pfid, DapperHelper cn)
        {
            return cn.Query<Node>("SELECT * FROM `fs_file` WHERE FileParentFolder = @pfid AND FileDeletionDate IS NULL LIMIT 0,2147483647;", new { pfid }).ToList();
        }

        public static bool deleteById(string fileId, DapperHelper cn)
        {
            return cn.ExecuteSql("DELETE FROM `fs_file` WHERE FileId = @fileId;", new { fileId });
        }

        public static bool deleteNode(Node file, string account, DapperHelper cn)
        {
            // 情况一：删除本地文件，删除文件记录

            // 情况二：无法删除云端文件，标记文件记录为删除状态
            return cn.ExecuteSql("UPDATE `fs_file` SET FileDeletionDate = @date,FileDeletor = @account WHERE FileId = @fid;", new { date = SystemUtil.accurateToDay(), account, fid = file.FileId });
        }

        public static bool updateFileNameById(string fileId, string newFileName, DapperHelper cn)
        {
            return cn.ExecuteSql("UPDATE `fs_file` SET FileName = @newFileName WHERE FileId = @fileId;", new { newFileName, fileId });
        }
    }
}
